#include <47func.h>
int main(int argc, char *argv[])
{
    // ./1_aqiang 192.168.118.128 1234
    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);//SOCK_DGRAM 意味着传输层是udp
    // 设置服务端地址信息
    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
    serverAddr.sin_port = htons(atoi(argv[2]));
    // 根据服务端地址sendto
    ssize_t sret = sendto(sockfd,"zaima",5,0,(struct sockaddr *)&serverAddr,sizeof(serverAddr));
    ERROR_CHECK(sret,-1,"sendto");
    
    char buf[4096];
    fd_set rdset;
    while(1){
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO,&rdset);
        FD_SET(sockfd,&rdset);
        select(sockfd+1,&rdset,NULL,NULL,NULL);
        if(FD_ISSET(STDIN_FILENO,&rdset)){
            bzero(buf,sizeof(buf));
            ssize_t ret = read(STDIN_FILENO,buf,sizeof(buf));
            if(ret == 0){
                sendto(sockfd,buf,0,0,(struct sockaddr *)&serverAddr,sizeof(serverAddr));
                break;//ctrl+d
            }
            sendto(sockfd,buf,strlen(buf),0,(struct sockaddr *)&serverAddr,sizeof(serverAddr));
        }
        if(FD_ISSET(sockfd,&rdset)){
            bzero(buf,sizeof(buf));
            ssize_t ret = recvfrom(sockfd,buf,sizeof(buf),0,NULL,NULL);
            if(ret == 0){
                printf("I quit\n");
                break;
            }
            printf("buf = %s\n", buf);
        }
    }
    close(sockfd);
    return 0;
}

